#!/bin/gawk -f
#
# Convert output from Whatif 'lista' command to AtomLIB format
# (extended with chain id)
# Problems:
#   - pseudo's in Val/Leu not mapped; need to derive from proton map
#   - translation of pseudo's to IUPAC not done
#
# Input format:
# 123456789012345678901234567890123456789012345678901234567890123456789012
#          1         2         3         4         5         6         7
# Residue:    95 GLU  (   5 ) B 1   (Prp= 1.00)
# Atom    X     Y     Z   Acc   B   WT   VdW  Colr   AtOK  Val
# 2HB    8.6   2.7  13.2  ---  0.0  1.0  1.0  250     +    0.00    1HB

BEGIN {
    "date" | getline date
    close( "date" )
    tmpfil = "wh2lib.tmp"
    vrsion = "1.5"
}

# store the residue info

$1 == "Residue:" {
    start = 1
    nam = $3
    num = $5
    chn = substr( $0, 29, 1 )
    if ( chn == " " ) chn = "."
    mdl = substr( $0, 30, 2 )
    next
}

!start { next }

NF == 0 { next }

/^SCRIPT/ { next }

$1 == "Atom" { next }

{
# get the standard name
    atstd = $1
# get the original name; replace by standard name if not listed
    at = substr( $0, 66 )
    if ( at == "" ) {
	at = atstd
    }
# change standard name from prefix to postfix
#    x = substr( atstd, 1, 1 ) 
#    if ( x ~ /[0-9]/ )
# 	atstd = substr( atstd, 2 ) x
# change original name from prefix to postfix - only for test purposes
#    x = substr( at, 1, 1 ) 
#    if ( x ~ /[0-9]/ )
# 	at = substr( at, 2 ) x

# fixing WHAT IF interpretation of terminus;-)
    if ( num == "OXT" ) num = lastnum

# fixing difference between original WHAT IF amide nomenclature and the
# one in use at PDB and BMRB
    if ( atstd == "HN" ) atstd = "H"

# print the mapping
    print "map", nam, num, chn, at, atstd > tmpfil
    lastnum = num
    count++
}

END {
    print "$ Aqua Version", vrsion, "DATA: Atom name maps found by WHATIF (", FILENAME, ")"
    print "$ FILE: AtomLIB CREATED:", date
    print "$ ATOM_COUNT:", count
    print "$ BEGIN_DATA:"
    system( "cat " tmpfil "; /bin/rm " tmpfil )
}

